<?php

use think\Db;

/**
 * Created by PhpStorm.
 * User: lub_lenovo
 * Date: 2017/11/8
 * Time: 14:13
 */

function p($arr)
{
    echo '<pre>';
    print_r($arr);
    echo '</pre>';
}

/**
 * 得到树形结构数据
 * @param $rows
 * @param $root_id
 *
 * @return array|null
 */
function build_tree($rows, $root_id)
{
    // global	$rows;
    $children = findChild($rows, $root_id);
    if (empty($children)) {
        return null;
    }
    foreach ($children as $k => $v) {
        # code...
        $rescurTree = build_tree($rows, $v['id']);
        if (null != $rescurTree) {
            $children[$k]['children'] = $rescurTree;
        }
    }
    return $children;
}

function findChild(&$arr, $id)
{
    $children = array();
    foreach ($arr as $k => $v) {
        if ($v['pid'] == $id) {
            $children[] = $v;
        }
    }
    return $children;
}


//订单号生成
function generateWorkNum()
{

    // $nextValArr=Db::query("select nextval('work_num') as next");
    $nextVal = null;
    $seqName = 'work_num';

    // 年关初始化单号自增值
    $mtime = Db::query("select `date` from work order by `date` desc limit 1;");
    if($mtime && $mtime[0] && date('Y', time())!=substr($mtime[0]["date"],0,4)){
        Db::query("update sequence set current_val=1 where seq_name='work_num';");
    }

    // 移动到了WorkLogic.add()中
    // Db::query("update sequence set current_val=current_val+increment_val where seq_name='$seqName';");
    $nextVal = "".Db::table('sequence')->where('seq_name', $seqName)->value('current_val');
    
    // $nextVal=$nextValArr[0]['next'];
    // 生成 201700001 形单号
    $count = strlen($nextVal);
    if ($count < 5) {
        for ($i = 0; $i < 5 - $count; $i++) {
            $nextVal = '0' . $nextVal;
        }
    }
    // 拼接上前面的年份
    $year = date('Y', time());
    return $year . $nextVal;
}